//uglify-js 依赖3.6.0
const fs=require('fs')
const path=require('path')
const uglifyPath=path.join(__dirname,'../node_modules/uglifyjs-webpack-plugin/node_modules/uglify-js')
try {
  if(fs.existsSync(uglifyPath)){
    if(fs.lstatSync(uglifyPath).isDirectory()){
      fs.rmdirSync(uglifyPath)
    }else{
      fs.unlinkSync(uglifyPath)
    }
    console.log('文件夹删除成功',uglifyPath)
  }
}catch (e) {
  console.log('文件夹删除失败')
}
function ChangeManifest(options) {}
const crypto = require('crypto');

var cryptoPassFunc = function(password) {
  const md5 = crypto.createHash('md5');
  return md5.update(password).digest('hex');
};
ChangeManifest.prototype.apply = function(compiler) {

  compiler.hooks.emit.tap('MyPlugin',function (compilation,params) {

    const reg1=/var \w+,(\w+)=document.createElement\("script"\);\w+\.charset="utf-8",\w+\.timeout=120,\w+\.nc&&\w+\.setAttribute\("nonce",\w+\.nc\),\w+\.src=/;
    const reg2=/var \w+=new Error;.+?\w+\.onerror=\w+.onload=\w+,document\.head\.appendChild\(\w+\)/;
    const reg3=/var \w+=document\.createElement\("link"\);\w+\.rel="stylesheet",\w+\.type="text\/css",\w+\.onload=(\w+),\w+\.onerror=function\(\w\)\{.+\},\w+.href=(\w+),document.getElementsByTagName\("head"\)\[0\]\.appendChild\(\w+\)/;
    const arr=Object.keys(compilation.assets).filter(function (filename) {
      if(/\.js$/.test(filename)){
        const info=compilation.assets[filename].source()
        if(reg1.test(info)&&reg2.test(info)&&reg3.test(info)){
          return true
        }
      }
      return false
    })
    if(arr.length === 0) {
      throw 'changeMainfest打包异常';
    }
    arr.forEach(function (filename) {
      let text=compilation.assets[filename].source();
      //修改jschunk
      text=text.replace(reg1,'var $1=')
      const o=RegExp.$1;
      text=text.replace(reg2,'LCache.loadAll('+o+')')
      //修改css
      text=text.replace(reg3,'LCache.loadAll($2,$1)')

      const nfilename= filename.replace(/\w{8}\.js/,cryptoPassFunc(text).substr(0,8)+'.js')
      if(nfilename!==filename){
        compilation.assets[nfilename]={
          source:function () {
            return text
          },
          size:function () {
            return text.length;
          }
        }
        delete compilation.assets[filename];

        for(let key in compilation.assets){
          if(/\.(js|json|html|css)$/.test(key)){
            const text2=compilation.assets[key].source().toString()
            const text3=text2.replace(filename,nfilename)
            if(text2!==text3){
              compilation.assets[key].source=function(){
                return text3
              }
            }
          }
        }
      }
    })

    compilation.assets['md5.js']=compilation.assets['md5.html'];
    delete compilation.assets['md5.html'];
  })
};

module.exports = ChangeManifest;
